package com.mitake.listener;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.mitake.timer.ClearDataJob;
import com.mitake.utils.Util;

public class MitakeServletContextListener implements ServletContextListener {
	
	private Scheduler  scheduler  = null;
	
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext servletContext =  sce.getServletContext();
		String[][] hosts = null;
		try {
			hosts = Util.getHost(servletContext.getRealPath("/"));
			servletContext.setAttribute("hosts", hosts);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			startScheduler(); //开启定时器
		} catch (SchedulerException e) {
			e.printStackTrace();
		}  
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		try{
			if(scheduler != null & scheduler.isStarted())
				scheduler.shutdown();	
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public  void startScheduler() throws SchedulerException{
		//首先，必需要取得一个Scheduler引用
		scheduler =StdSchedulerFactory.getDefaultScheduler();
		String time = "0 0 0 * * ?";  // 每天24点触发
		//jobs可以在scheduled的sched.start()方法前被调用
		
		JobDetail job =JobBuilder.newJob(ClearDataJob.class)
			    .withIdentity("job1", "group1")
			    .build();
		CronTrigger trigger = TriggerBuilder.newTrigger()
				.withIdentity("trigger1", "group1")
				.withSchedule(CronScheduleBuilder.cronSchedule(time))
				.build();
		scheduler.scheduleJob(job, trigger);
		scheduler.start();
	}
	
	public static void main(String[] args) {
		System.out.println(System.getProperty("java.library.path"));
	}
	

}
